﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;

using SBPweb.PlAzureNet.Server.Data.Actors;
using SBPweb.PlAzureNet.Server.Data.Context;

using SBPweb.PlAzureNet.Server.Library.Operations;

namespace SBPweb.PlAzureNet.Server.Library.Services
{

    partial class DataService : IPleasureDataServiceContract
    {

        public Pleasure FetchOnePleasureById(int pleasureId)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                return context.Pleasures.FirstOrDefault(x => x.Id == pleasureId).GetTranslated(context);
            }
        }

        public Pleasure FetchOnePleasureByName(string pleasureName, string cultureCode)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                string ci = GetCurrentContextCulture().Name;

                if (string.IsNullOrEmpty(cultureCode))
                {
                    cultureCode = ci;
                }

                var trans = context.Translations.FirstOrDefault(x => x.CultureCode == cultureCode && x.Value == pleasureName);
                if (trans == null)
                {
                    return null;
                }

                return context.Pleasures.FirstOrDefault(x => x.NameId == trans.TermId).GetTranslated(context);
            }
        }

        public IEnumerable<Pleasure> FetchAllPleasures()
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                return context.Pleasures.Select(x => x.GetTranslated(context)).ToList();
            }
        }

        public IEnumerable<MetaInfo> FetchAllPleasureMetaInfoByPleasure(Pleasure pleasure)
        {
            return FetchAllPleasureMetaInfoByPleasureId(pleasure.Id);
        }

        public IEnumerable<MetaInfo> FetchAllPleasureMetaInfoByPleasureId(long pleasureId)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                var xpmis = context.xPleasureMetaInfos.Where(x => x.PleasureId == pleasureId).Select(x => x.MetaInfoId);
                return context.MetaInfos.Where(x => xpmis.Contains(x.Id));
            }
        }

        public IEnumerable<MetaInfo> FetchAllPleasureMetaInfoByPleasureName(string pleasureName, string cultureCode)
        {
            return FetchAllPleasureMetaInfoByPleasure(FetchOnePleasureByName(pleasureName, cultureCode));
        }

    }

}